<template>
  <div class="article-detail-page">
    <!-- 顶部信息区 -->
    <ArticleHeader :article="article" :comments-count="comments.length" />

    <!-- 文章内容区 -->
    <ArticleContent
      ref="articleContentRef"
      :content="article.content"
      :toc-items="tocItems"
      :preview-theme="previewTheme"
      :description="article.description"
      @theme-change="previewTheme = $event"
      @toc-update="tocItems = $event"
    />

    <!-- 底部信息区 -->
    <div class="article-bottom">
      <ArticleAuthorCard
        :author="article.author"
        :article-id="article.id"
        :prev="prevArticle"
        :next="nextArticle"
        :liked="siteStats.liked"
        :likes="siteStats.likes"
        :stats="{
          articleCount: siteStats.articleCount,
          tagCount: siteStats.tagCount,
          categoryCount: siteStats.categoryCount,
        }"
        @nav="handleNav"
      />
    </div>

    <!-- 交互按钮区 -->

    <!-- 评论区 -->
    <ArticleComments
      :comments="comments"
      :article-id="article.id"
      :pagination="commentsPagination"
      @submit="loadComments(article.id)"
      @page-change="(page) => loadComments(article.id, page)"
    />

    <!-- 打赏弹窗 -->
    <ArticleAppreciation :show="showAppreciation" @close="showAppreciation = false" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getArticleDetail, getArticleCardInfo } from '@/api/article'
import ArticleHeader from './components/ArticleHeader.vue'
import ArticleContent from './components/ArticleContent.vue'
import ArticleAuthorCard from './components/ArticleAuthorCard.vue'
import ArticleComments from './components/ArticleComments.vue'
import { getArticleComments } from '@/api/article'
import ArticleAppreciation from './components/ArticleAppreciation.vue'

// ArticleDetailPage 文章详情页

// 文章详情（后端数据映射，含安全默认值）
const article = ref({
  id: null,
  title: '',
  coverImage: '',
  content: '',
  publishDate: '',
  updateDate: '',
  views: 0,
  likes: 0,
  author: { id: null, name: '', avatar: '', bio: '', email: '' },
  category: { id: null, name: '' },
  tags: [],
  source: '',
  copyright: '',
})

const tocItems = ref([])
const previewTheme = ref('github')
const comments = ref([])
const commentsPagination = ref({ total: 0, current: 1, pages: 1, size: 10 })
const prevArticle = ref(null)
const nextArticle = ref(null)
const showAppreciation = ref(false)

// 路由与数据加载
const route = useRoute()
const router = useRouter()
// 头像生成：QQ邮箱用QQ头像，否则从默认池中按邮箱稳定取一张
const defaultAvatars = [
  'https://cdn.jsdelivr.net/gh/tsundoku-lab/cdn-assets/avatar/avatar1.png',
  'https://cdn.jsdelivr.net/gh/tsundoku-lab/cdn-assets/avatar/avatar2.png',
  'https://cdn.jsdelivr.net/gh/tsundoku-lab/cdn-assets/avatar/avatar3.png',
  'https://cdn.jsdelivr.net/gh/tsundoku-lab/cdn-assets/avatar/avatar4.png',
  'https://cdn.jsdelivr.net/gh/tsundoku-lab/cdn-assets/avatar/avatar5.png',
  'https://cdn.jsdelivr.net/gh/tsundoku-lab/cdn-assets/avatar/avatar6.png',
]
function getAvatarForEmail(email) {
  if (!email || typeof email !== 'string') return defaultAvatars[0]
  const match = email.trim().match(/^([1-9][0-9]{4,10})@qq\.com$/i)
  if (match) {
    return `https://q2.qlogo.cn/headimg_dl?dst_uin=${match[1]}&spec=100`
  }
  let sum = 0
  for (let i = 0; i < email.length; i++) sum = (sum + email.charCodeAt(i)) >>> 0
  return defaultAvatars[sum % defaultAvatars.length]
}
const siteStats = ref({ runDays: 0, pv: 0, uv: 0, liked: false, likes: 0 })

async function loadData(id) {
  try {
    const data = await getArticleDetail(id)
    article.value = {
      id: data.id,
      title: data.title,
      coverImage: data.picUrl,
      description: data.description,
      content: data.content,
      publishDate: data.createOn,
      updateDate: data.updateOn,
      views: data.viewsNum,
      likes: data.likeNum,
      author: {
        id: data.author?.id,
        name: data.author?.nickname || data.author?.username || data.author?.name,
        avatar: data.author?.avatar,
        bio: data.author?.bio,
        email: data.author?.email,
      },
      category: data.category
        ? { id: data.category.id, name: data.category.name }
        : { id: null, name: '' },
      tags: Array.isArray(data.tags) ? data.tags.map((t) => ({ id: t.id, name: t.name })) : [],
      source: '原创',
      copyright: '本文为博主原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。',
    }
    try {
      const card = await getArticleCardInfo(id)
      if (card) {
        article.value.author = {
          ...article.value.author,
          name: card.nickname || article.value.author?.name,
          avatar: card.avatarUrl || article.value.author?.avatar,
          bio: card.sign || article.value.author?.bio,
          tagInfo: card.userTag || '',
          verified: !!card.userTag,
          socials: article.value.author?.socials || {},
        }
        article.value.likes =
          typeof card.likeCount === 'number' ? card.likeCount : article.value.likes
        prevArticle.value = card.prevId ? { id: card.prevId, title: card.prevTitle } : null
        nextArticle.value = card.nextId ? { id: card.nextId, title: card.nextTitle } : null
        siteStats.value = {
          articleCount: card.articleCount ?? 0,
          tagCount: card.tagCount ?? 0,
          categoryCount: card.categoryCount ?? 0,
          liked: !!card.isLike,
          likes: typeof card.likeCount === 'number' ? card.likeCount : 0,
        }
      }
    } catch (error) {
      console.warn('获取文章卡片信息失败:', error)
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    article.value = {}
  }
}

onMounted(async () => {
  const id = route.params.id || route.query.id
  if (id) await loadData(id)
  // 加载评论
  if (id) await loadComments(id)
})

watch(
  () => route.params.id,
  async (id, oldId) => {
    if (id && id !== oldId) {
      await loadData(id)
      await loadComments(id)
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
  },
)

function handleNav(target) {
  if (target && target.id) {
    router.push({ name: 'ArticleDetail', params: { id: target.id } })
  }
}

/**
 * 递归处理评论节点，包括嵌套的replies
 * @param {Object} comment - 评论对象
 * @param {number} level - 当前层级
 * @param {Object} parentComment - 父评论对象（用于判断回复逻辑）
 * @returns {Object} 处理后的评论节点
 */
function processCommentNode(comment, level = 1, parentComment = null) {
  // 判断是否为自己回复自己
  const isSelfReply =
    parentComment &&
    comment.email === parentComment.email &&
    comment.nickname === parentComment.nickname

  // 判断是否为直接回复一级评论（parentId 和 rootId 相等）
  const isDirectReplyToRoot = comment.parentId === comment.rootId

  // 设置回复显示逻辑
  let replyToUser = ''
  if (level > 1 && !isSelfReply && !isDirectReplyToRoot) {
    // 非自己回复自己且非直接回复一级评论时，优先使用 replyToNickname，其次使用父评论的昵称
    if (comment.replyToNickname) {
      replyToUser = comment.replyToNickname
    } else if (parentComment?.nickname) {
      replyToUser = parentComment.nickname
    }
  }

  const commentNode = {
    id: comment.id,
    nickname: comment.nickname,
    content: comment.content,
    avatar: getAvatarForEmail(comment.email),
    createdAt: comment.createOn,
    likes: comment.likeNum || 0,
    liked: !!comment.isLike,
    isAdmin: comment.isAdmin === '1',
    parentId: comment.parentId,
    replyToNickname: comment.replyToNickname,
    replyToUser: replyToUser, // 优化后的回复对象显示
    replies: [], // 子评论数组
    level: level, // 评论层级，用于UI展示
    isSelfReply: isSelfReply, // 标记是否为自己回复自己
    isDirectReplyToRoot: isDirectReplyToRoot, // 标记是否为直接回复一级评论
    // 新增的设备信息
    ipRegion: comment.ipRegion,
    deviceType: comment.deviceType,
    browser: comment.browser,
    os: comment.os,
  }

  // 递归处理子评论
  if (comment.replies && Array.isArray(comment.replies) && comment.replies.length > 0) {
    commentNode.replies = comment.replies.map((reply) => {
      // 二级评论层级为2，三级及以上也为2（与二级并排显示）
      const replyLevel = level === 1 ? 2 : 2
      return processCommentNode(reply, replyLevel, commentNode)
    })
  }

  return commentNode
}

/**
 * 构建多级评论树结构
 * @param {Array} comments - 评论列表
 * @returns {Array} 构建好的评论树
 */
function buildCommentTree(comments) {
  if (!Array.isArray(comments)) return []

  // 只处理一级评论（parentId === '-1'），子评论通过replies数组递归处理
  return comments
    .filter((comment) => comment.parentId === '-1')
    .map((comment) => processCommentNode(comment, 1))
}

/**
 * 加载文章评论
 * @param {string|number} articleId - 文章ID
 * @param {number} page - 页码，默认为1
 */
async function loadComments(articleId, page = 1) {
  try {
    const response = await getArticleComments(articleId, '1', page, 10)
    console.log('评论数据:', response)

    // 使用新的评论树构建函数
    comments.value = buildCommentTree(response?.records || [])

    // 保存分页信息
    commentsPagination.value = {
      total: response?.total || 0,
      current: response?.current || 1,
      pages: response?.pages || 1,
      size: response?.size || 10,
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    comments.value = []
    commentsPagination.value = { total: 0, current: 1, pages: 1, size: 10 }
  }
}
</script>

<style lang="scss" scoped>
@import url('https://fontsapi.zeoseven.com/578/main/result.css');

.article-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 24px 100px 24px;
  background: var(--bg-color);
  border-radius: 18px;
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.08);
  @media (max-width: 900px) {
    max-width: 100vw;
    padding: 12px 0 60px 0;
    border-radius: 0;
    box-shadow: none;
  }
}
.article-bottom {
  margin-top: 48px;
  display: flex;
  flex-direction: column;
  gap: 32px;
}
</style>
